package com.example.demo2;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RequestMapping("T2")
@RestController
public class Test2 {
    @RequestMapping("/t1")
    public String getFile(@RequestParam MultipartFile file) throws IOException {
String name=file.getOriginalFilename();
file.transferTo(new File("D:\\temp\\"+file.getOriginalFilename()));
return "文件上传成功"+name;
    }

    @RequestMapping("t2")
    public String t2(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
if(cookies!=null){
    for (Cookie e:cookies) {
        System.out.println("Name:"+e.getName()+"   value:"+e.getValue());
    }
    return "获取cookie成功";
}
return "获取cookie失败";
    }


    @RequestMapping("t3")
public String t3(@CookieValue("age") String age){
        return "获取cookie中age的值为"+age;
    }

    //设置session

    @RequestMapping("t4")
    public String setSession(HttpServletRequest request){
        //从cookie中获取sessionID，根据sessionID获取session对象
        HttpSession session= request.getSession();
session.setAttribute("name","张三");
session.setAttribute("age",19);
return "设置session成功";
    }

    @RequestMapping("t5")
    public String getSession(HttpServletRequest request){
        HttpSession session= request.getSession(false);
        if(session==null){
            return "用户未登录";
        }
        String name= (String) session.getAttribute("name");
        return "用户登录，用户名为："+name;
    }


    @RequestMapping("t6")
public String getSession2(HttpSession session){
       String name=(String) session.getAttribute("name");
       return "获取用户姓名："+name;
    }

    @RequestMapping("t7")
    public String getSession3(@SessionAttribute("name")String name){
        return "获取用户姓名："+name;
    }

    @RequestMapping("t8")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("user-Agent");
        return "从Header中获取userAgent的信息:"+userAgent;
    }

    @RequestMapping("t9")
    public String getHeader(@RequestHeader("user-Agent")String userAgent){
        return "从Header中获取userAgent的信息:"+userAgent;
    }


}
